#include<bits/stdc++.h>
#define ONLINE_JUDGE
#define ll long long
#define ull unsigned long long
using namespace std;

const ll N = 1e6 + 10, INF = 0x3f3f3f3f, MOD = 998244353;

ll n;

ll ksm(ll a, ll b)
{
    ll res = 1;
    while (b) {
        if (b & 1) res = res * a % MOD;
        a = a * a % MOD, b >>= 1;
    }
    return res;
}


ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); }
ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }
ll inv(int x, int y) {
    for (int i = 2;i < n / i;i++) {
        if (!y % i) return i;
        return x;
    }
}
void solve()
{
    int x, y;
    cin >> x >> y;
    if (x > y) swap(x, y);
    if (x == y) {
        cout << "0" << endl;
        return;
    }
    if (!y % x) {
        cout << y << endl;
        return;
    }
    ll xx = inv(x, y);
    cout << inv(xx, y) + +xx<<endl;
}

signed main()
{
    // ios::sync_with_stdio(0);
    // cin.tie(0);cout.tie(0);
#ifndef ONLINE_JUDGE
    std::istringstream in(R"()");
    std::cin.rdbuf(in.rdbuf());
#endif
    ll T = 1;
    cin>>T;
    for (ll i = 1;i <= T;i++) {
        solve();
    }
}